package sisi.ports;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;


/**
 * PortWindow.java - Controller class for <i>Port window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 20/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class PortWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxPort
	private Window windowPort, windowEditPort;
	private Textbox tbCerca;
	private Listbox boxPort;

	private List tutti_i_ports;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object portItem;
	private Port modPort;
	// edit
	private Intbox id;

	private Textbox portname, region, contactname1, contactname2, contactname3, telcn1, telcn2, telcn3;
	private Textbox faxcn1, faxcn2, faxcn3, note, email, website, city, sn, latdegrees, ew, londegrees;
	private Combobox cbCountry;

	public void onCreate$windowPort(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutti_i_ports = new PortController().getPortList(null);
		listModelList.addAll(tutti_i_ports);
		boxPort.setModel(listModelList);
		boxPort.setItemRenderer(new PortItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutti_i_ports.size(); i++) {
				Port port = (Port)tutti_i_ports.get(i);
				if (port.getId()==idSelezionato.intValue()){
					boxPort.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_i_ports = new PortController().getPortList(tbCerca
				.getValue());
		listModelList.addAll(tutti_i_ports);
		boxPort.setModel(listModelList);
		boxPort.setItemRenderer(new PortItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxPort.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oPort = boxPort.getSelectedItem().getAttribute(
					"rigaPort");
			String codiceSelezionato = ""+((Port) oPort).getId();
			Sessions.getCurrent().setAttribute("codicePortSelezionato",
					codiceSelezionato);
			windowPort.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxPort.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Port to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxPort", boxPort);
				Window finestraEditPort = (Window) Executions.createComponents(
						"/editPort.zul", null, map);
				finestraEditPort.doModal();
			}
		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class PortItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Port) data).getId()).setParent(li);
			new Listcell(((Port) data).getPortname()).setParent(li);
			new Listcell(((Port) data).getCountry()).setParent(li);
			li.setAttribute("rigaPort", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT PORT: NEW/MODIFY
	@SuppressWarnings("deprecation")
	public void onCreate$windowEditPort(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxPort = (Listbox) args.get("boxPort");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}
		
		if (!lNuovo) {
			portItem = boxPort.getSelectedItem().getAttribute("rigaPort");
			modPort = new PortController().refreshPort((Port) portItem);
			portItem = modPort;
			windowEditPort.setTitle("Edit Port");
			portname.setFocus(true);
			id.setValue(modPort.getId());
			portname.setValue(modPort.getPortname());
			//country.setValue(modPort.getCountry());
			region.setValue(modPort.getRegion());
			contactname1.setValue(modPort.getContactname1());
			contactname2.setValue(modPort.getContactname2());
			contactname3.setValue(modPort.getContactname3());
			telcn1.setValue(modPort.getTelcn1());
			telcn2.setValue(modPort.getTelcn2());
			telcn3.setValue(modPort.getTelcn3());
			faxcn1.setValue(modPort.getFaxcn1());
			faxcn2.setValue(modPort.getFaxcn2());
			faxcn3.setValue(modPort.getFaxcn3());
			note.setValue(modPort.getNote());
			email.setValue(modPort.getEmail());
			website.setValue(modPort.getWebsite());
			city.setValue(modPort.getCity());
			sn.setValue(modPort.getSn());
			latdegrees.setValue(modPort.getLatdegrees());
			ew.setValue(modPort.getEw());
			londegrees.setValue(modPort.getLondegrees());			
		} else {
			windowEditPort.setTitle("New Port");
			portname.setFocus(true);
		}
		List<String> listCountry = new PortController().getCountryList();
		ListModelList lm = new ListModelList(listCountry);
		
		if (!lNuovo){
			if (!modPort.getCountry().isEmpty()){
				cbCountry.setValue(modPort.getCountry());
				lm.addSelection(modPort.getCountry());
				//cbCountry.setSelectedIndex(lm.indexOf(modPort.getCountry())); // non funziona!!
			}
		}
		
		cbCountry.setModel(lm);

		
	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditPort.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modPort = new Port();
		} else {

		}
		String testoMsg = "";
		
		modPort.setId(id.getValue());
		modPort.setPortname(General.toUpperAncheNull(portname.getValue()));
		modPort.setCountry(General.toUpperAncheNull(cbCountry.getValue()));
		modPort.setRegion(General.toUpperAncheNull(region.getValue()));
		modPort.setCity(General.toUpperAncheNull(city.getValue()));
		modPort.setContactname1(General.toUpperAncheNull(contactname1.getValue()));
		modPort.setContactname2(General.toUpperAncheNull(contactname2.getValue()));
		modPort.setContactname3(General.toUpperAncheNull(contactname3.getValue()));
		modPort.setEmail(email.getValue());
		modPort.setEw(ew.getValue());
		modPort.setFaxcn1(faxcn1.getValue());
		modPort.setFaxcn2(faxcn2.getValue());
		modPort.setFaxcn3(faxcn3.getValue());
		modPort.setLatdegrees(latdegrees.getValue());
		modPort.setLondegrees(londegrees.getValue());
		modPort.setNote(note.getValue());
		modPort.setRegion(General.toUpperAncheNull(region.getValue()));
		modPort.setSn(sn.getValue());
		modPort.setTelcn1(telcn1.getValue());
		modPort.setTelcn2(telcn2.getValue());
		modPort.setTelcn3(telcn3.getValue());
		modPort.setWebsite(website.getValue());

	
		if (lNuovo){
			new PortController().addPort(modPort);
			testoMsg = "Adding Port: "+ General.trimNull( modPort.getPortname() );
		} else {
			new PortController().updatePort(modPort);
			testoMsg = "Updating Port: "+ General.trimNull( modPort.getPortname() );			
		}
		
		General.showNotify( testoMsg, windowEditPort);
		
		windowEditPort.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxPort.getListModel();
			lml.add(modPort);
			boxPort.setSelectedIndex(lml.indexOf(modPort));
		} else {
			ListModelList lml = (ListModelList) boxPort.getListModel();
			Object oPortItem = boxPort.getSelectedItem().getAttribute("rigaPort");
			if (lml.indexOf(oPortItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oPortItem), modPort);
			}
		}		
	}
	
	
}
